<template>
  <div class="article-management">
    <el-card class="main-card">
      <template #header>
        <div class="card-header">
          <h2>文章管理</h2>
          <el-button type="primary" @click="handleAdd" :icon="Plus">新增文章</el-button>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="文章标题" class="form-item">
            <el-input v-model="searchForm.title" placeholder="请输入文章标题"></el-input>
          </el-form-item>
<!--          <el-form-item label="分类" class="form-item">-->
<!--            <el-select v-model="searchForm.category" placeholder="请选择分类" clearable style="width: 200px;">-->
<!--              <el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.name"></el-option>-->
<!--            </el-select>-->
<!--          </el-form-item>-->
<!--          <el-form-item label="标签" class="form-item">-->
<!--            <el-select v-model="searchForm.tags" multiple placeholder="请选择标签" clearable style="width: 300px;">-->
<!--              <el-option v-for="item in tagList" :key="item.id" :label="item.name" :value="item.name"></el-option>-->
<!--            </el-select>-->
<!--          </el-form-item>-->
          <el-form-item class="form-item">
            <el-button type="primary" @click="onSearch" :icon="Search">搜索</el-button>
            <el-button @click="resetSearch" :icon="Refresh">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- 表格区域 -->
      <div class="table-area">
        <el-table :data="articleList" style="width: 100%" @selection-change="handleSelectionChange" :stripe="true" :border="true">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column label="特色头像" width="180">
            <template #default="scope">
              <el-image
                  style="width: 100px; height: 100px"
                  :src="scope.row.viewImage"
                  :zoom-rate="1.2"
                  :max-scale="7"
                  :min-scale="0.2"
                  :preview-src-list="[scope.row.viewImage]"
                  :initial-index="4"
                  preview-teleported
                  fit="cover"
              />
            </template>
          </el-table-column>
          <el-table-column prop="title" label="文章标题" min-width="180">
            <template #default="scope">
              <el-link type="primary" @click="viewArticle(scope.row)">{{ scope.row.title }}</el-link>
            </template>
          </el-table-column>
          <el-table-column prop="categoryList" label="分类" width="180">
            <template #default="scope">
              <el-tag v-for="category in scope.row.categoryList" :key="category.id" class="tag-item" :color="category.color">{{ category.name }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="tagList" label="标签" width="180">
            <template #default="scope">
              <el-tag v-for="tag in scope.row.tagList" :key="tag.id" class="tag-item" :color="tag.color">{{ tag.name }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="author" label="作者" width="120"></el-table-column>
          <el-table-column
              prop="createTime"
              label="创建时间"
              width="160"
              :formatter="formatDate"
          ></el-table-column>
          <el-table-column
              prop="updateTime"
              label="更新时间"
              width="160"
              :formatter="formatDate"
          ></el-table-column>
          <el-table-column prop="views" label="浏览量"></el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button size="small" type="primary" @click="handleEdit(scope.row)" :icon="Edit">编辑</el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row)" :icon="Delete">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页区域 -->
      <div class="pagination-area">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5, 10, 20]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="articleTotal">
        </el-pagination>
      </div>
    </el-card>

    <!-- 新增/编辑文章对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="60%" destroy-on-close>
      <el-form :model="articleForm" label-width="80px" class="article-form">
        <el-form-item>
          <!-- 上传图片 -->
          <el-upload class="avatar-uploader" accept="image/*" :show-file-list="false"
                     :http-request="uploadMainImg">
            <img v-if="articleForm.viewImage" :src="articleForm.viewImage" class="avatar">
            <i v-else class="avatar-uploader-icon">
              <el-icon>
                <Plus />
              </el-icon>
            </i>
          </el-upload>
        </el-form-item>
        <el-form-item label="标题">
          <el-input v-model="articleForm.title"></el-input>
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="articleForm.categoryIds" multiple placeholder="请选择分类">
            <el-option v-for="(item,index) in categoryList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标签">
          <el-select v-model="articleForm.tagIds" multiple placeholder="请选择标签">
            <el-option v-for="(item,index) in tagList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="内容">
          <!--   markdown组件化  :theme="'dark'"   -->
          <md-editor v-model="articleForm.content" @onUploadImg="onUploadImg"  />
<!--          <v-md-editor v-model="articleForm.content"/>-->
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitArticle">发布</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search, Refresh, Plus, Delete, Edit } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {MdEditor} from 'md-editor-v3';
import 'md-editor-v3/lib/style.css';
import { toast } from '@/composables/util.js'
import { selectAllArticle, selectByArticleId, deleteByArticleId, addArticle, updateArticle} from '@/api/back/article.js'
import { deleteByCategoryId, selectAllCategory } from '@/api/back/category.js'
import { uploadEditImage } from '@/api/common/web.js'
import { selectAllTag } from '@/api/back/tag.js'
import { uploadAvatarImage } from '@/api/common/web.js'
import store from "@/store"




const categoryList = ref([])
const tagList = ref([])

// 搜索表单数据
const searchForm = reactive({
  title: '',
  category: '',
  tags: []
})

// 文章列表数据
const articleList = ref([
  // { id: 1, title: 'Vue3新特性', category: '技术', tags: ['Vue', 'JavaScript'], author: '张三' },
  // { id: 2, title: 'React Hooks详解', category: '技术', tags: ['React', 'JavaScript'], author: '李四' },
  // ... 更多文章数据
])

// 分页相关数据
const currentPage = ref(1)
const pageSize = ref(5)
const articleTotal = ref(100)


// 选中的文章
const selectedArticles = ref([])

// 对话框相关数据
const dialogVisible = ref(false)
const dialogTitle = ref('新增文章')
const articleForm = reactive({
  id: null,
  title: '',
  categoryList: [],
  tagList: [],
  content: ''
})

onMounted(async () => {
  InitDate()
})

//格式化一下时间
const formatDate = (row, column, cellValue, index) => {
  if (cellValue) {
    const date = new Date(cellValue);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
  }
  return '';
}



//初始化数据
const InitDate = async () =>{

  await selectAllCategory({pageNum:1,pageSize:100}).then((res) => {
    categoryList.value = res.data.data.list
    console.log(categoryList.value)
  })
  await selectAllTag({pageNum:1,pageSize:100}).then((res) => {
    tagList.value = res.data.data.list
    console.log(tagList.value)
  })
  await selectAllArticle({pageNum: currentPage.value,pageSize: pageSize.value}).then((res) => {
    articleList.value=res.data.data.list
    articleTotal.value = res.data.data.total
    articleList.value.forEach(item => {
      item.author = store.state.userInfo.username
    })
  })

}


// 搜索方法
const onSearch = () => {
  console.log('搜索条件：', searchForm)
  selectAllArticle({title: searchForm.title,pageSize: pageSize.value,pageNum: currentPage.value}).then(res => {
    articleList.value=res.data.data.list
    articleTotal.value = res.data.data.total
    articleList.value.forEach(item => {
      item.author = store.state.userInfo.username
    })
  })
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = Array.isArray(searchForm[key]) ? [] : ''
  })
}

//上传图片
const uploadMainImg = function (file) {
  //创建表单结构
  const data = new FormData()
  data.append('file', file.file)

  uploadAvatarImage(data).then(res => {
    console.log(res)
    articleForm.viewImage = res.data.data[0].url
  })
}

// 新增文章
const handleAdd = () => {
  dialogTitle.value = '新增文章'
  Object.keys(articleForm).forEach(key => {
    articleForm[key] = Array.isArray(articleForm[key]) ? [] : null
  })
  articleForm.content = "" //这里不能让为null，因为markdown解析器需要传递字符串！
  dialogVisible.value = true
}

// 编辑文章
const handleEdit = (row) => {
  dialogTitle.value = '编辑文章'
  let categoryIdArray = []
  let tagIdArray = []
  row.categoryList.forEach(item => {
    categoryIdArray.push(item.id)
  })
  row.tagList.forEach(item => {
    tagIdArray.push(item.id)
  })
  console.log("categoryIdArray",categoryIdArray)
  console.log("tagIdArray",tagIdArray)
  row.categoryIds = categoryIdArray
  row.tagIds = tagIdArray

  Object.assign(articleForm, row)
  console.log("编辑行",articleForm)
  dialogVisible.value = true
}

// 删除文章
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除这篇分类吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteByArticleId(row.id).then(res=>{
      toast("删除成功!","success")
      InitDate()
    })
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    })
  })
}

// 查看文章
const viewArticle = (row) => {
  console.log('查看文章：', row)
  // 这里应该跳转到文章详情页或打开预览对话框
}

// 提交文章
const submitArticle = () => {
  console.log('提交文章：', articleForm)
  articleForm.userId = store.state.userInfo.id
  if(articleForm.id){
    updateArticle(articleForm).then(res => {
      if(res.data.code === '200'){
        toast( '文章更新成功',"success")
        InitDate()
      }
    })
  }else{
    addArticle(articleForm).then(res => {
      if(res.data.code === '200'){
        toast( '文章发布成功',"success")
        InitDate()
      }
    })
  }

  dialogVisible.value = false
  InitDate()
}

// 表格选择变化
const handleSelectionChange = (val) => {
  //可以进行多次删除操作
  selectedArticles.value = val
}

// 改变每页显示数量
const handleSizeChange = (val) => {
  pageSize.value = val
  // 这里应该重新加载文章列表
  selectAllArticle({pageNum: currentPage.value,pageSize: pageSize.value, title: searchForm.title}).then(res => {
    articleList.value=res.data.data.list
    articleTotal.value = res.data.data.total
    articleList.value.forEach(item => {
      item.author = store.state.userInfo.username
    })
  })
}

// 改变页码
const handleCurrentChange = (val) => {
  currentPage.value = val
  selectAllArticle({pageNum: currentPage.value,pageSize: pageSize.value, title: searchForm.title}).then(res => {
    articleList.value=res.data.data.list
    articleTotal.value = res.data.data.total
    articleList.value.forEach(item => {
      item.author = store.state.userInfo.username
    })
  })
}

const onUploadImg = async (files, callback) => {
  const res = await Promise.all(
      files.map((file) => {
        return new Promise((rev, rej) => {
          const form = new FormData();
          form.append('file', file);
            uploadEditImage(form).then(res => {
              console.log(res);
              // 获取图片链接
              const imageUrl = res.data.data;
              rev(imageUrl);
            })
        });
      })
  );

  callback(res);
};
</script>

<style scoped>
.article-management {
  padding: 20px;

  min-height: 100vh;
}

.main-card {
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.card-header h2 {
  margin: 0;
  color: #1f2f3d;
}

.search-area {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.form-item {
  margin-bottom: 10px;
  flex-grow: 1;
}

/* 确保最后一个表单项(按钮组)不会过度拉伸 */
.form-item:last-child {
  flex-grow: 0;
}

.table-area {
  margin-bottom: 20px;
}

.tag-item {
  margin-right: 5px;
  margin-bottom: 5px;
}

.pagination-area {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.article-form {
  max-width: 600px;
  margin: 0 auto;
}

.el-dialog__body {
  padding-top: 10px;
}

.dialog-footer {
  text-align: right;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>